<?php
/**
 * Created by PhpStorm.
 * User: august
 * Date: 2021/4/1
 * Time: 14:17
 */

namespace Aug\Tools;


class Helper
{
    /**
     * 格式化输出结果
     *
     * author: august 2021/4/1
     * @param $message
     * @param int|null $code
     * @param array $data
     * @return array
     */
    public static function formatResult($message, ?int $code = 0, array $data = [])
    {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];
    }

    /**
     * 返回json格式
     *
     * author: august 2021/4/1
     * @param $message
     * @param int|null $code
     * @param array $data
     * @return false|string
     */
    public static function returnJson($message, ?int $code = 0, array $data = [])
    {
        header("Content-Type:application/json;charset=utf-8");
        $res = Helper::formatResult($message, $code, $data);
        return json_encode($res, true);
    }

    const ERROR_FILE_NOT_EXIST = '错误：文件不存';

    public static function checkFileExist($file, $throw = true)
    {
        if ($throw && !file_exists($file)) {
            throw new \Exception(self::ERROR_FILE_NOT_EXIST, 1);
        }
        return file_exists($file);
    }

    /**
     * 获取uniqid（还有一些其他算法 比如雪花算法等，这里提供简单的两个php自带函数实现的）
     *
     * author: august 2021/4/10
     * @param string $method
     * @return int|string
     */
    public static function getUniqueId($method = 'simple_uniqid')
    {
        $allowedMethods = ['uniqid', 'session_id', 'simple_uniqid'];
        if (!in_array($method, $allowedMethods)) {
            throw new \UnexpectedValueException("不支持的算法,仅支持" . join(',', $allowedMethods), 1);
        }
        $uid = 0;
        $prefix = substr(md5(php_uname('n') . getmypid() . mt_rand(1, 999999)), 8, 16);
        switch ($method) {
            case 'simple_uniqid':
                $uid = uniqid(mt_rand(), true);
                break;
            case 'uniqid':
                $uid = uniqid($prefix, true);
                break;
            case "session_id":
                if (version_compare(PHP_VERSION, '7.1.0') < 0) {
                    throw new \RuntimeException("session_id算法，必须php版本>7.1", 2);
                }
                $uid = session_create_id();
                break;
        }
        return $uid;
    }

}